package cn.mlamp4;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.UUID;

@SpringBootApplication
@RestController
public class Application {
    private ObjectMapper jsonMapper = new ObjectMapper();
    String testtoken = "tzptoken";
    HashSet<String> tokens = new HashSet<>();

    int[][] first24 = Arrays.copyOfRange(Heart.all, 0, 24);
    int getnum = 2;//每次给几个
    String flag = "qqwweerrfafa";

    @PostMapping("/set-get-num")
    public Object setGetNum(@RequestParam("num") int num) {
        if (num < 0 || num > Heart.CNT) {
            return "没有哦";
        }
        getnum = num;
        return "ok";
    }

    @GetMapping("/get-first-24")
    public Object getInit(HttpServletResponse response) {
        String token = UUID.randomUUID().toString();
        tokens.add(token);
        response.setHeader("mycsrftoken", token);
        return first24;
    }

    @GetMapping("/get")
    public Object get(
            HttpServletResponse response,
            @RequestParam("from") int from,
            @RequestHeader("mycsrftoken") String csrf) {
        String token = UUID.randomUUID().toString();
        tokens.add(token);
        response.setHeader("mycsrftoken", token);

        if (csrf == null) {
            response.setStatus(400);
            return "不是从浏览器请求的吧, 你猜怎么被发现的";
        }
        if (!tokens.contains(csrf) && !csrf.equals(testtoken)) {
            response.setStatus(400);
            return "不是从浏览器请求的吧, 你猜怎么被发现的";
        }
        tokens.remove(csrf);

        if (from < 0 || from >= Heart.CNT) {
            response.setStatus(400);
            return "没有哦";
        }
        int to = Math.min(Heart.all.length, from + getnum);
        return Arrays.copyOfRange(Heart.all, from, to);
    }

    @PostMapping("/check")
    public Object check(@RequestBody int[][] data) {
        if (data.length != Heart.CNT) {
            return "坐标不够还原图形!";
        }
        if (Arrays.deepEquals(data, Heart.all) || Arrays.deepEquals(data, Heart.all1)) {
            return "哇, 你找到我了, 这是你的领奖码:" + flag;
        } else {
            return "坐标值不正确!";
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
